package com.bank.sdb.util.encryption;

/**
 * ��������ѹ����Ӧ����. 
 * 
 * ����CRYPT�㷨����ѹ���ͽ�ѹ. 
 */
public class Base64
{

    public Base64()
    {
    }

    public static byte[] decode(char[] ac)
    {
        int i = ac.length;
        for(int j = 0; j < ac.length; j++)
        {
            byte byte0 = codes[ac[j] & 0xff];
            if(byte0 < 0 && ac[j] != '=')
                i--;
        }

        int k = ((i + 3) / 4) * 3;
        if(i > 0 && ac[i - 1] == '=')
            k--;
        if(i > 1 && ac[i - 2] == '=')
            k--;
        byte abyte0[] = new byte[k];
        int l = 0;
        int i1 = 0;
        int j1 = 0;
        for(int k1 = 0; k1 < ac.length; k1++)
        {
            byte byte1 = codes[ac[k1] & 0xff];
            if(byte1 >= 0)
            {
                i1 <<= 6;
                l += 6;
                i1 |= byte1;
                if(l >= 8)
                {
                    l -= 8;
                    abyte0[j1++] = (byte)(i1 >> l & 0xff);
                }
            }
        }

        if(j1 != abyte0.length)
            throw new Error("Miscalculated data length (wrote " + j1 + " instead of " + abyte0.length + ")");
        else
            return abyte0;
    }

    public static char[] encode(byte[] abyte0)
    {
        char ac[] = new char[((abyte0.length + 2) / 3) * 4];
        int i = 0;
        for(int j = 0; i < abyte0.length; j += 4)
        {
            boolean flag = false;
            boolean flag1 = false;
            int k = 0xff & abyte0[i];
            k <<= 8;
            if(i + 1 < abyte0.length)
            {
                k |= 0xff & abyte0[i + 1];
                flag1 = true;
            }
            k <<= 8;
            if(i + 2 < abyte0.length)
            {
                k |= 0xff & abyte0[i + 2];
                flag = true;
            }
            ac[j + 3] = alphabet[flag ? k & 0x3f : 64];
            k >>= 6;
            ac[j + 2] = alphabet[flag1 ? k & 0x3f : 64];
            k >>= 6;
            ac[j + 1] = alphabet[k & 0x3f];
            k >>= 6;
            ac[j] = alphabet[k & 0x3f];
            i += 3;
        }

        return ac;
    }

    private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
    private static byte[] codes;

    static
    {
        codes = null;
        codes = new byte[256];
        for(int i = 0; i < 256; i++)
            codes[i] = -1;

        for(int j = 65; j <= 90; j++)
            codes[j] = (byte)(j - 65);

        for(int k = 97; k <= 122; k++)
            codes[k] = (byte)((26 + k) - 97);

        for(int l = 48; l <= 57; l++)
            codes[l] = (byte)((52 + l) - 48);

        codes[43] = 62;
        codes[47] = 63;
    }
}
